package com.example.lib_patrol.add

import androidx.lifecycle.viewModelScope
import com.example.lib_common.mvi.BaseViewModel
import com.example.lib_common.mvi.ResponseEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class AddPatrolViewModel : BaseViewModel<AddPatrolRepository,AddPatrolState>() {
    override fun createRepo(): AddPatrolRepository {
        return AddPatrolRepository()
    }

    override fun createState(): AddPatrolState {
        return AddPatrolState(ResponseEntity(0,"", arrayListOf(PointEntity())),
            ResponseEntity(0,"", PointEntity()),
            ResponseEntity(0,"", arrayListOf(GroupEntity())))
    }
    fun requestAll(){
        mutableContainer.updateRequestState { copy(
            request = true
        ) }
        viewModelScope.launch(Dispatchers.IO) {
            repo.requestAllRepairPoint().flowOn(Dispatchers.IO)
                .collect{
                    mutableContainer.updateRequestState { copy(
                        request=false,complete=true
                    ) }
                    mutableContainer.updateUiState { copy(
                        entity=it
                    ) }
                }
        }
    }
    fun requestAddPatrol(map: HashMap<String,Any>){
        mutableContainer.updateRequestState { copy(
            request = true
        ) }
        viewModelScope.launch(Dispatchers.IO) {
            repo.requestAddPatrols(map).flowOn(Dispatchers.IO)
                .collect{
                    mutableContainer.updateRequestState { copy(
                        request=false,complete=true
                    ) }
                    mutableContainer.updateUiState { copy(
                        entity1=it
                    ) }
                }
        }
    }
    fun requestAllGroup(){
        mutableContainer.updateRequestState { copy(
            request = true
        ) }
        viewModelScope.launch(Dispatchers.IO) {
            repo.requestAllGroup().flowOn(Dispatchers.IO)
                .collect{
                    mutableContainer.updateRequestState { copy(
                        request=false,complete=true
                    ) }
                    mutableContainer.updateUiState { copy(
                        entity2=it
                    ) }
                }
        }
    }
}